<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" style="margin-left:5px;" @click="exportData" :loading="exportLoading">导出
    </el-button>
    <div class="fr" v-if="stocktaking['status']==2" style="margin-left:5px;">
      <el-button type="success" @click="updateStocktakingQty" :loading="submmitLoadingV">保存调账数据</el-button>
    </div>
    <el-button class="filter-item fr" type="success" style="margin-left: 5px" plain @click="research">查询</el-button>
    <el-input class="fr filter-item" style="width: 200px;margin-left: 5px" placeholder="输入物料查询" clearable
      prefix-icon="el-icon-search" @keyup.enter.native="research" @clear="research"
      v-model="query.queryString.material"></el-input>
    <el-select class="filter-item fr" style="width: 160px;" v-model="query.queryString.status" placeholder="选择有差异的明细"
      filterable clearable>
      <el-option v-for="(item,index) in statusOptions" :key="index" :value="item.value" :label="item.label">
      </el-option>
    </el-select>

    <div class="filter-container">
      <!--<el-select class="filter-item" style="width: 200px;" v-model="query.warehouse_id" placeholder="选择盘点单"
                       clearable>
                <el-option v-for="i in warehouseList" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>-->
      <div class="filter-item">
        <span style="vertical-align: sub">{{stocktaking.order_no}}</span>
        <span style="vertical-align: sub">{{stocktaking.order_desc}}</span>
        <span class="ml-5"
          :style="{verticalAlign:'sub',color:statusColor[stocktaking.status]}">{{status[stocktaking.status]}}</span>
      </div>

      <!-- <el-input style="width: 300px;" placeholder="输入单点单号按回车" clearable prefix-icon="el-icon-search"
                       class="filter-item"
                       @keyup.enter.native="research" @clear="research" v-model="query.queryString"></el-input>-->
      <!--<el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
            </el-button>-->
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="v">
        <span v-if="v.key==='take_qty'">
          <span v-if="stocktaking['status']==2">
            <span v-if=" v.row.editflag">
              <span>
                <el-input v-model="v.row[v.key]" style="width:80px" size="mini" placeholder=""></el-input>
              </span>
              <span>
                <el-button type="success" size="mini" style="margin-left: 5px" @click="createItem(v.row)"
                  :loading="v.row.submmitLoading" icon="el-icon-check" circle></el-button>
                <el-button style="margin-left: 5px" type="danger" size="mini" @click="closeItem(v.index)"
                  icon="el-icon-close" circle></el-button>
              </span>
            </span>
            <a href="javascript:void(0)" v-else @click="saveShow(v.row)" style="color:#409EFF">{{v.row[v.key]}}</a>
          </span>
          <span v-else @click="saveShow(v.row)">{{v.row[v.key]}}</span>
        </span>
        <span v-else-if="v.key=='took_qty'">
          <a href="javscript:void(0)" @click.prevent="openLogDialog(v.row)" style="color:#409EFF">{{v.row[v.key]}}</a>
        </span>
        <span v-else-if="v.key=='difference_qty'">
          <span v-if="v.row[v.key]>0" class="text-label bg-green">{{v.row[v.key]}}</span>
          <span v-else-if="v.row[v.key]<0" class="text-label bg-red">{{v.row[v.key]}}</span>
          <span v-else>{{v.row[v.key]}}</span>
        </span>
        <span v-else>{{v.row[v.key]}}</span>
      </template>
      <!--<template v-slot:operation="v">
                <a href="#" class="text-blue" @click.prevent="deleteItem(v.row,v.$index)">保存调账</a>
                <a href="#" class="text-yellow" @click.prevent="openLogDialog(v.row,v.$index)">查看日志</a>
            </template>-->
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.curPage" :limit.sync="query.pageSize"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submmitLoading="submmitLoading" :visible.sync="editFormVisible"></z-form-dialog>

    <el-dialog title="扫码日志" :visible.sync="scanLogDialog" width="80%">
      <z-table :list="logList" :tableProps="logTableProps" v-loading="pageLoadingLog" :columns="logColumns">
      </z-table>
      <z-pagination :pagination="pagination" :total="logTotal" :page.sync="logQuery.curPage"
        :limit.sync="logQuery.pageSize" @change="getList"></z-pagination>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
export default {
  mixins: [commonMixin],
  name: 'stocktakingDiffrence',
  data: function () {
    return {
      api: this.$api.stocktaking,
      apiList: this.$api.stocktaking + 'getbyid',
      name: '盘点单明细',
      columns: [
        /*{title: '盘点单号', key: 'order_no', width: 180},*/
        { title: '仓库', key: 'warehouse_name_code', width: 100 },
        { title: '物料', key: 'material_name_code', width: 180 },
        { title: '库位', key: 'stock_code', width: 80 },
        { title: '供应商', key: 'vender_name_code' },
        { title: '批次', key: 'lot_date_code', width: 140 },
        { title: '账面数量', key: 'qty', width: 80 },
        { title: '已盘数量', key: 'took_qty', width: 80 },
        { title: '差异数量', key: 'difference_qty', width: 80 },
        { title: '调账数量', key: 'take_qty', width: 180 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      tableProps: {
        border: true,
        opsColWith: 130,
        hideOperations: true,
      },
      fields: [
        { title: '仓库', key: 'warehouse_id', name: 'select', options: [], required: true },
        {
          title: '输入物料',
          key: 'material',
          name: 'textarea',
          props: { rows: 5 },
        },
        {
          title: '盘点单说明',
          key: 'order_desc',
          name: 'textarea',
          props: {},
        },
        { title: '备注', key: 'remarks', name: 'textarea' },
      ],
      query: {
        queryString: { status: '', material: '' },
        pageSize: 10,
        curPage: 1,
      },
      logColumns: [
        { title: '扫描条码', key: 'sn', width: 140 },
        { title: '仓库', key: 'warehouse_name_code', width: 110 },
        { title: '物料', key: 'material_name_code', width: 180 },
        { title: '库位', key: 'stock_code', width: 80 },
        { title: '供应商', key: 'vender_name_code', width: 140 },
        { title: '批次', key: 'lot_date_code', width: 110 },
        { title: '数量', key: 'qty', width: 80 },
        { title: '盘点人', key: 'modify_user', width: 100 },
        { title: '盘点时间', key: 'modify_time', width: 140 },
      ],
      logTableProps: {
        border: true,
        opsColWith: 130,
        hideOperations: true,
      },
      submmitLoading: false,
      pageLoadingLog: false,
      submmitLoadingV: false,
      value: '',
      stocktaking: {},
      logQuery: {
        queryString: null,
        pageSize: 10,
        curPage: 1,
      },
      logTotal: 0,
      logList: [],
      scanLogDialog: false,
      status: { 0: '计划中', 1: '盘点中', 2: '核对中', 9: '已完成' },
      statusColor: { 0: '#909399', 1: '#E6A23C', 2: '#67C23A', 9: '#409EFF' },
      tranData: { data: {}, detail: [] },
      statusOptions: [
        { value: '3', label: '全部' },
        { value: '1', label: '有差异的' },
        // { value: '1', label: '使用' },
        { value: '2', label: '无差异的' },
      ],
    }
  },
  methods: {
    openLogDialog(v) {
      this.scanLogDialog = true
      this.logQuery.id = v.id
      this.getStocktakingLogs()
    },

    getStocktakingLogs() {
      this.pageLoadingLog = true
      this.$request(this.api + 'getStocktakingLogs', this.logQuery)
        .then((r) => {
          this.pageLoadingLog = false
          this.logList = this.formatList(r.list)
          this.logTotal = r.total
        })
        .catch(() => {
          this.pageLoadingLog = false
        })
    },
    saveShow(v) {
      let index = this.list.findIndex((x) => x.id == v.id)
      this.list[index].editflag = true
    },
    createItem(item) {
      let index = this.list.findIndex((x) => x.id == item.id)
      let data = { id: item.id, order_id: item.order_id, take_qty: item.take_qty }
      this.list[index].submmitLoading = true
      this.$request(this.api + 'updateStocktakingQtyItem', data, 'post')
        .then((r) => {
          this.list[index].submmitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editFormVisible = false
          //this.getList()
          this.list[index]['editflag'] = false
        })
        .catch(() => {
          this.list[index].submmitLoading = false
        })
    },
    closeItem(index) {
      this.list[index].editflag = false
    },
    updateStocktakingQty() {
      this.$confirm('保存后会调整库存，确认保存？', '操作确认').then(() => {
        this.submmitLoadingV = true
        this.$request(this.api + 'updateStocktakingQty/' + this.stocktaking['id'], '', 'post')
          .then((r) => {
            this.submmitLoadingV = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getList()
          })
          .catch(() => {
            this.submmitLoadingV = false
          })
      })
    },
    formatList(list) {
      //依据实际需求处理
      let tmp = _.cloneDeep(list)
      return tmp.map((i) => {
        i.editflag = false
        if (!!i.vendor_code) {
          i.vender_name_code = i.vendor_code + ' ' + i.vendor_name
        }
        i.material_name_code = i.key_part_no + ' ' + i.key_part_name
        i.warehouse_name_code = i.warehouse_code + ' ' + i.warehouse_name
        i.submmitLoading = false
        return i
      })
    },

    fetchParams() {
      this.query.queryString.order_id = this.$route.params.id
      this.getList()
    },
    getList() {
      this.pageLoading = true
      let url = this.api + 'getlist'
      if (this.apiList) {
        url = this.apiList
      }
      this.$request(url, this.formatQuery(this.query))
        .then((r) => {
          this.pageLoading = false
          this.stocktaking = r['data']
          this.list = this.formatList(r['detail']['detailResult'])
          this.total = r['detail']['total']
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    exportData() {
      let url = this.apiList
      this.exportLoading = true
      this.$request(url, this.formatQuery(this.query, true))
        .then((r) => {
          var exprotList = this.formatList(r['detail']['detailResult'])
          import('@/vendor/Export2Excel')
            .then((excel) => {
              const filterVal = this.columns.map((item) => {
                return item.key
              })
              const tHeader = this.columns.map((item) => {
                return item.title || item.key
              })
              const data = exprotList.map((v) => filterVal.map((j) => v[j]))
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: this.name + '_' + dayjs().format('YYYYMMDD'),
              })
              this.exportLoading = false
            })
            .catch((e) => {
              this.exportLoading = false
            })
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
  },
  created: function () {
    this.query.queryString.status = '3'
    this.fetchParams()
  },
}
</script>
<style scoped>
.el-button--mini.is-circle {
  padding: 3px !important;
}
</style>
